import React, { useMemo, useState, useEffect } from 'react'
import getCinemaListAction from '../redux/action/getCinemaListAction'
import { connect } from 'react-redux'

function Search(props) {
    const [mytext, setText] = useState("")

    let { cinemaList, getCinemaListAction } = props

    useEffect(() => {
        if (cinemaList.length === 0) {
            getCinemaListAction()
        }
    }, [cinemaList, getCinemaListAction])

    const getCinemaList = useMemo(
        () =>
            cinemaList.filter(item => item.name.toUpperCase().includes(mytext.toUpperCase()) ||
                item.address.toUpperCase().includes(mytext.toUpperCase()))
        ,
        [cinemaList, mytext]
    )

    return (
        <div>
            <input value={mytext} onChange={(evt) => {
                setText(evt.target.value)
            }} />
            {
                getCinemaList.map(item =>
                    <dl key={item.cinemaId}>
                        <dt>{item.name}</dt>
                        <dd>{item.address}</dd>
                    </dl>
                )
            }
        </div>
    )
}

const mapStateToProps = (state) => ({
    cinemaList: state.CinemaReducer.list
})

const mapDispatchToProps = {
    getCinemaListAction
}

export default connect(mapStateToProps, mapDispatchToProps)(Search)